package top.zackyoung.mq.rocketmq.demo.transaction;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @version 1.0
 * @description:
 * @author: ZackYoung
 * @date: 2021/4/3 17:52
 */
@Service
@RocketMQTransactionListener(txProducerGroup = "tx-producer-group")
public class OrderServiceImplListener implements RocketMQLocalTransactionListener {
    @Resource
    OrderService orderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        String txId = (String) message.getHeaders().get("txId");
        try {
            // 执行本地事务
            Order order = (Order) o;
            orderService.createOrder(order, txId);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 消息回查
        String txId = (String) message.getHeaders().get("txId");
        // 本地事务执行成功
        return !txId.isEmpty() ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;
    }
}
